package com.duguo.dynamicmvc.view.resource;

import java.io.IOException;

import javax.servlet.ServletContext;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.ResourceUtils;
import org.springframework.web.context.ServletContextAware;

public class ResourceResolverImpl implements ResourceResolver, ServletContextAware {

	private ResourceLoader resourceLoader = new DefaultResourceLoader();

	private String protectedExtenstion = ".*class$|.*xml$|.*properties$";

	private ServletContext servletContext;

	public Resource resolve(String resourceName) {
		return resolve(resourceName, false);
	}

	public Resource resolve(String resourceName, boolean ignoreSecurityCheck) {
		Resource resource = getServletContentPathResource(resourceName, ignoreSecurityCheck);
		try {
			if(resource!=null && resource.getFile().isDirectory())
				resource=null;
		} catch (IOException ignore) {}
		if (resource == null) {
			resource = getClassPathResource(resourceName, ignoreSecurityCheck);
			if (resource == null) {
				resource = getRawResource(resourceName, ignoreSecurityCheck);
			}
		}
		return resource;
	}

	private Resource getServletContentPathResource(String resourceName, boolean ignoreSecurityCheck) {
		if (ignoreSecurityCheck || !resourceName.startsWith("/WEB-INF/")) {
			Resource resource = new FileSystemResource(servletContext.getRealPath(resourceName));
			if (resource.exists()) {
				return resource;
			}
		}
		return null;
	}

	private Resource getClassPathResource(String resourceName, boolean ignoreSecurityCheck) {
		if (ignoreSecurityCheck || !resourceName.matches(protectedExtenstion)) {
			Resource resource = resourceLoader.getResource(ResourceUtils.CLASSPATH_URL_PREFIX + resourceName);
			if (resource.exists()) {
				return resource;
			}
		}
		return null;
	}

	private Resource getRawResource(String resourceName, boolean ignoreSecurityCheck) {
		if (ignoreSecurityCheck || !resourceName.matches(protectedExtenstion)) {
			Resource resource = resourceLoader.getResource(resourceName);
			if (resource.exists()) {
				return resource;
			}
		}
		return null;
	}

	public void setProtectedExtenstion(String protectedExtenstion) {
		this.protectedExtenstion = protectedExtenstion;
	}

	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
}
